<html>
	<head>
		<meta charset="utf-8"> 
		<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
		 
		<title>Gilstar</title>
		<link href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" rel="stylesheet" type="text/css" />
		<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
		<script src="http://code.jquery.com/jquery.js"></script>
		<script src="http://code.jquery.com/mobile/latest/jquery.mobile.min.js"></script>
		<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3.3&sensor=true"></script>
		<script src="json2.js"></script>
		<script src="modernizr-1.7.min.js"></script>
		<script>
		//<![CDATA[
		var map;
		var currentLocation;
		
		var req;
		
		$(function() 
		{
			$("#Home").live("pageshow", function(event, ui){
				//alert("home page show!");
			});
			$("#Register").live("pageshow", function(event, ui){
				//alert("Register page show!");
			});
			$("#Search").live("pageshow", function(event, ui){
				//alert("Search page show!");
				getPerformanceList();
			});
		});
		
		function initialize()
		{
			if(Modernizr.geolocation)	//geolocation support check
			{
				navigator.geolocation.getCurrentPosition(showMap, handleError, {enableHighAccuracy : true, maximumAge : 75000});
			}
			else
			{
				alert("위치정보 서비스가 지원되지 않습니다.");
			}
		}
		
		function showMap(position)
		{
			//coords객체는 지구상 위치를 나타내는 위도, 경도 등의 정보를 가지고 있다.
			//각 속성에는 다음과 같은 값들이 존재한다.
			//coords.latitude, coords.longitude, coords.altitude, coords.acccuracy, coords.altitudeAccuracy,
			//coords.heading(정북 방향에서부터의 시계방향 각도), coords.speed coords.timestamp 
			//coords의 속성 중 latitude, longitude, accuracy 세 가지 속성에는 반드시 값이 존재한다. 
			var latitude = position.coords.latitude;	//십진법 각도
			var longigude = position.coords.longitude;	//십진법 각도.
			
			currentLocation = new google.maps.LatLng(latitude, longigude);
			
			var myOptions = { zoom: 15, center: currentLocation, mapTypeId: google.maps.MapTypeId.ROADMAP };
			map = new google.maps.Map(document.getElementById("mapView"), myOptions);			
			
			
			
			getPerformanceListForMap();
			//var marker = new google.maps.Marker(
			//		{
			//			position : currentLocation,
			//			title : "my location",
			//			map : map
			//		});
		}
		
		function handleError(err)
		{
			var code = err.code;
			//code의 종류에 1번은 사용자가 위치정보를 공유안함, 2번은 네트워크에 문제 발생, 3번은 시간이 너무 오래 걸림
			//4번은 알 수 없는 오류 발생.
			var message = err.message;		//최종 사용자를 위한 용도가 아님. 
			
		}
		
		function getJSON(url, json)
		{
			var requestStr = JSON.stringify(json, replacer);
			
			$.ajax(
				{
					url: url,
					data: requestStr,
					type: "POST",
					success: function(data)
					{
						var resultObject = jQuery.parseJSON(data);
						jsonResponseHandler(resultObject);
					}
				});
		}
		
		function jsonResponseHandler(result)
		{
			if(result.ResultCode == -1)			//처리 도중 실패.
			{
				alert(result.ResultMessage);
			}
			else if(result.ResultCode == 0)	//성공적으로 처리 완료.
			{
				if(req == "GET_PERFORMANCE_FROM_MAP")
				{
					alert("현위치에 등록된 공연 리스트를 가져옵니다. 등록 건수 : " + result.ResultMethod.length);
					for(var nIndex = 0; nIndex < result.ResultMethod.length; nIndex++)
					{
						var items = result.ResultMethod[nIndex];	//access by array index.
						var latlng = new google.maps.LatLng(items.latitude, items.longitude);
						var marker = new google.maps.Marker(
								{
									position : latlng,
									title : items.title + ", 시간 : " + items.time,
									map : map
								});
					}
				}
				else if(req == "REGISTER_PERFORMANCE")
				{
					var performance_seq = result.ResultMethod[0].performance_seq;
					alert("길거리 공연이 등록되었습니다. " + performance_seq);
					$.mobile.changePage("#Home", "flip");
				}
				else if(req == "GET_PERFORMANCE_LIST")
				{
					alert("총 " + result.ResultMethod.length + "개가 검색되었습니다.");
					$("#performanceList").empty();
					for(var i = 0; i < result.ResultMethod.length; i++)
					{
						var items = result.ResultMethod[i];
						$("<li>" + items.title + "/" + items.artist + "/" + items.time + "</li>").appendTo($("#performanceList"));
					}
					$("#performanceList").listview("refresh");
				}
			}
		}
		function getPerformanceListForMap()
		{
			var url = "http://gilstar.com:8080/gilstar/Performance.jsp";
			var o = new Object();
			o.req = "GET_PERFORMANCE_FROM_MAP";
			
			req = o.req;
			
			//get north_east and south_west
			var bounds = map.getBounds();
			//alert( + "," + bounds.getSouthWest());
			
			var north_east = new Object();
			north_east.latitude = bounds.getNorthEast().lat();
			north_east.longitude = bounds.getNorthEast().lng();
			
			var south_west = new Object();
			south_west.latitude = bounds.getSouthWest().lat();
			south_west.longitude = bounds.getSouthWest().lng();
			
			o.north_east = north_east;
			o.south_west = south_west;
			
			getJSON(url, o);
			
			
		}
		
		function replacer(key, value) 
		{
		    if (typeof value === 'number' && !isFinite(value)) 
		    {
		        return String(value);
		    }
		    return value;
		}
		
		function goRegisterView()
		{
			$.mobile.changePage("#Register", "flip");
		}
		
		function registPerformance()
		{
			var so = $("form[name=registerForm]").serializeArray();
			
			var o = {};
			
			$.each(so, function()
				{
					var key = this.name;
					var value;
					if(this.value != null)
					{
						value = this.value;
					}
					else
					{
						value = "";
					}
					if(key == "title" || key == "artist" || key == "content")
					{
						value = encodeURL(value);
					}
					else if(key == "latitude")
					{
						value = currentLocation.lat();
					}
					else if(key == "longitude")
					{
						value = currentLocation.lng();
					}
					else if(key == "req")
					{
						req = value;
					}
					o[key] = value;
				});
			var url = "http://gilstar.com:8080/gilstar/Performance.jsp";
			getJSON(url, o);
		}
		
		function encodeURL(str){
		    var s0, i, s, u;
		    s0 = "";                // encoded str
		    for (i = 0; i < str.length; i++)
		    {
		        s = str.charAt(i);
		        u = str.charCodeAt(i);          // get unicode of the char
		        if (s == " ")
		        {
		        	s0 += "20";	// SP should be converted to "+"
		        }
		        else 
		        {
	                if ((u >= 0x0) && (u <= 0x7f))    // single byte format
	                {
	                    s = "0"+u.toString(16);
	                    s0 += s.substr(s.length-2);
	                }
	                else if (u > 0x1fffff)	// quaternary byte format (extended)
	                {    
	                    s0 += (oxf0 + ((u & 0x1c0000) >> 18)).toString(16);
	                    s0 += (0x80 + ((u & 0x3f000) >> 12)).toString(16);
	                    s0 += (0x80 + ((u & 0xfc0) >> 6)).toString(16);
	                    s0 += (0x80 + (u & 0x3f)).toString(16);
	                }
	                else if (u > 0x7ff)	// triple byte format
	                {        
	                    s0 += (0xe0 + ((u & 0xf000) >> 12)).toString(16);
	                    s0 += (0x80 + ((u & 0xfc0) >> 6)).toString(16);
	                    s0 += (0x80 + (u & 0x3f)).toString(16);
	                }
	                else 			// double byte format
	                {                      
	                    s0 += (0xc0 + ((u & 0x7c0) >> 6)).toString(16);
	                    s0 += (0x80 + (u & 0x3f)).toString(16);
	                }
		        }
		    }

		    return s0;
		}
		
		function goSearch()
		{
			$.mobile.changePage("#Search", "flip");
		}
		
		function getPerformanceList()
		{
			var url = "http://gilstar.com:8080/gilstar/Performance.jsp";
			var object = new Object();
			object.req = "GET_PERFORMANCE_LIST";
			req = object.req;
			getJSON(url, object);
		}
		
		//]]>
		</script>
	</head>
	<body onload="initialize()">
	
	<div data-role="page" id="Home">
		
		<div data-role="header">
			<h1>Gilstar home</h1>
			<div data-role="navbar">
				<ul>
					<li><a href="#Home" class="ui-btn-active">홈</a></li>
					<li><a href="#Register" data-transition="flip">등록하기</a></li>
					<li><a href="#Search" data-transition="flip">검색하기</a></li>
				</ul>
			</div><!-- /navbar -->
		</div>
		<div data-role="content" style="width: 100%; height: 100%;">
			<div id="mapView" style="width: 90%; height: 300"></div>
			<button onclick="getPerformanceListForMap()">현재 위치 공연정보</button>
			<!-- 
			<button onclick="goRegisterView()">등록하기</button>
			<button onclick="goSearch()">검색</button>
			 -->
		</div>
		<div data-role="footer">
			<h4>&copy; 2011 Street Aritist</h4>
		</div>
	</div>
	<div data-role="page" id="Register">
		<div data-role="header">
			<h1>Gilstar home</h1>
			<div data-role="navbar">
				<ul>
					<li><a href="#Home" data-transition="flip">홈</a></li>
					<li><a href="#Register" class="ui-btn-active">등록하기</a></li>
					<li><a href="#Search" data-transition="flip">검색하기</a></li>
				</ul>
			</div><!-- /navbar -->
			<!-- 
			<a href="#Home" data-rel="back" data-direction="reverse" data-transition="flip">back</a>
			-->
		</div>
		<div data-role="content" style="width: 100%; height: 100%;">
			<div data-role="fieldcontain">
				<form action="#" name="registerForm">
					<label for="title">Title:</label>
					<input type="hidden" name="req" value="REGISTER_PERFORMANCE">
					<input type="hidden" name="latitude">
					<input type="hidden" name="longitude">
					<input type="hidden" name="email" value="winwin5907@naver.com">
	    			<input type="text" name="title" id="title"/>
	    			<label for="artist">Artist:</label>
	    			<input type="text" name="artist" id="artist"/>
	    			<label for="category">Category:</label>
	    			<select name="category" id="category">
	    				<option value="music">음악 공연</option>
	    				<option value="performance">행위 공연</option>
	    				<option value="exhibition">전시 공연</option>
	    				<option value="others">기타 공연</option>
	    			</select>
	    			<label for="date">시작일</label>
	    			<input type="date" name="date" id="date"/>
	    			<label for="time">시작시간</label>
	    			<input type="time" name="time" id="time"/>
	    			<label for="content">내용</label>
	    			<textarea rows="20" cols="5" name="content" id="content"></textarea>
	    			<label for="url_link1">첨부링크1</label>
	    			<input type="text" name="url_link1" id="url_link1"/>
	    			<label for="url_link2">첨부링크2</label>
	    			<input type="text" name="url_link2" id="url_link2"/>
	    			<label for="url_link3">첨부링크3</label>
	    			<input type="text" name="url_link3" id="url_link3"/>
	    			<label for="sns_url">sns주소</label>
	    			<input type="text" name="sns_url" id="sns_url"/>
				</form>
				<!-- 
				<form action="FileUpload.jsp" method="post" enctype="multipart/form-data" name="fileUploadForm">
					<input type="hidden" name="performance_seq" id="performance_seq">
					<label for="file">이미지 첨부</label>
					<input type="file" name="file" id="file">
				</form>
				 -->
    			<button onclick="registPerformance();">등록하기</button>
			</div>
		</div>
		<div data-role="footer">
			<h4>&copy; 2011 Street Aritist</h4>
		</div>
	</div>
	<div data-role="page" id="Search">
		<div data-role="header">
			<h1>Gilstar home</h1>
			<div data-role="navbar">
				<ul>
					<li><a href="#Home" data-transition="flip">홈</a></li>
					<li><a href="#Register" data-transition="flip">등록하기</a></li>
					<li><a href="#Search" class="ui-btn-active">검색하기</a></li>
				</ul>
			</div><!-- /navbar -->
		</div>
		<div data-role="content" style="width: 100%; height: 100%;">
			<ul data-role="listview" data-inset="true" data-theme="c" data-dividertheme="b" id="performanceList"> 
			</ul>
		</div>
		<div data-role="footer">
			<h4>&copy; 2011 Street Aritist</h4>
		</div>
	</div>
	</body>
</html>